package com.rookieci.totp.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.rookieci.lib.TimeConstant;
import com.rookieci.totp.R;
import com.rookieci.totp.mode.QRCodeMode;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Created by 磁磁帅 on 2025/8/16 0016.
 * 功能：
 */
public class QrCodeAdapter extends RecyclerView.Adapter<QrCodeAdapter.QrCodeViewHolder> {
    private Context context;
    private List<QRCodeMode> modeList;
    private OnAdapterListener onAdapterListener;

    public QrCodeAdapter(Context context, List<QRCodeMode> modeList) {
        this.context = context;
        this.modeList = modeList;
    }

    @NonNull
    @Override
    public QrCodeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_qrcode_list, parent, false);
        return new QrCodeViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull QrCodeViewHolder holder, int position) {
        QRCodeMode mode = modeList.get(position);
        holder.setMode(mode);
    }

    @Override
    public int getItemCount() {
        return modeList.size();
    }

    public QrCodeAdapter setOnAdapterListener(OnAdapterListener onAdapterListener) {
        this.onAdapterListener = onAdapterListener;
        return this;
    }

    public class QrCodeViewHolder extends RecyclerView.ViewHolder {
        public QrCodeViewHolder(@NonNull View itemView) {
            super(itemView);
            textContent = itemView.findViewById(R.id.textContent);
            textTime = itemView.findViewById(R.id.textTime);
            View textDel = itemView.findViewById(R.id.textDel);

            textDel.setOnClickListener(v -> {
                if (onAdapterListener == null) return;
                onAdapterListener.onDelClick(mode);
            });
            itemView.setOnClickListener(v -> {
                if (onAdapterListener == null) return;
                onAdapterListener.onAdapterClick(mode);
            });
        }

        private TextView textContent, textTime;
        private QRCodeMode mode;

        public void setMode(QRCodeMode mode) {
            this.mode = mode;

            textContent.setText(mode.codeStr);
            textTime.setText(TimeConstant.getDataTime2(mode.timeL));
        }
    }

    public interface OnAdapterListener {
        void onAdapterClick(QRCodeMode mode);

        void onDelClick(QRCodeMode mode);
    }
}
